package spring.boot.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import spring.boot.entity.SysPermission;
import spring.boot.entity.SysUser;
import spring.boot.mapper.SysPermissionMapper;
import spring.boot.mapper.SysUserMapper;

@Service
public class UserService implements UserDetailsService {

	@Autowired
	private SysUserMapper userMapper;
	
	@Autowired
	private SysPermissionMapper sysPermissionMapper;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser user = userMapper.selectByUsername(username);
		if (user == null) {  
            throw new UsernameNotFoundException("UserName " + username + " not found");  
        }else{
			List<SysPermission> permissions = sysPermissionMapper.selectByUserId(user.getId());
			List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
			for (SysPermission permission : permissions) {
			    if (permission != null && permission.getPermissionCode()!=null) {
			    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getPermissionCode());
			    //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
			    grantedAuthorities.add(grantedAuthority);
			    }
			}
			return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
        }
	}

}
